<?php
class ReportsController extends AppController {
    var $uses = array('Item', 'ItemIn', 'ItemOut', 'UnitCode');

    var $pageTitle = 'Report';

    function index() {
    }

/**
 * Report of all stock of items, ordered by item's name
 * direct rendered to print html
 */
    function stocks() {
        $this->layout = 'printhtml';
        Configure::write('debug', 0);
        $items = $this->Item->find('all', array(
            'fields' => array('Item.id', 'Item.name', 'Unit.name'),
            'order' => 'Item.name ASC'
        ));

        $terlaris = array(
            'item' => array(),
            'total' => 0
        );
        $minimum = array(
            'item' => array(),
            'total' => null
        );
        foreach ($items as $key => $item) {
            $items[$key]['Item']['penerimaan'] = $this->__getStockIn( $item['Item']['id'] );
            $items[$key]['Item']['pengeluaran'] = $this->__getStockOut( $item['Item']['id'] );
            $items[$key]['Item']['stok'] = $items[$key]['Item']['penerimaan'] - $items[$key]['Item']['pengeluaran'];

            if ( is_null( $minimum['total'] )  ) {
                $minimum['total'] = $items[$key]['Item']['stok'];
            }


            if ( $items[$key]['Item']['pengeluaran'] > $terlaris['total'] ) {
                $terlaris['total'] = $items[$key]['Item']['pengeluaran'];
                $terlaris['item'] = $item;
            }

            if ( $items[$key]['Item']['stok'] < $minimum['total'] ) {
                $minimum['total'] = $items[$key]['Item']['stok'];
                $minimum['item'] = $item;
            }
        }

        $this->set('items', $items);
        $this->set('terlaris', $terlaris);
        $this->set('minimum', $minimum);
    }

/**
 *  report stock per item, this just
 *  show form to select one item and its period.
 *  Rendering print page on stocks_per_item
 */
    function stocks_per_item_id() {
        $this->set('items', $this->Item->find('list', array(
                'fields' => array('Item.id', 'Item.name'),
                'order' => 'Item.name ASC'
            ))
        );
        $this->set('path', 'http://' . $_SERVER['HTTP_HOST'] . $this->webroot . '/reports/stocks_per_item_ext/');
        $periodes = $this->ItemIn->find('list', array('fields' => array('ItemIn.date_in', 'ItemIn.date_in')));
        $periodes[date('Y-m-d')] = date('Y-m-d');
        $this->set('periodes', $periodes);
    }

    function stocks_per_item($item_id, $periode = null) {
        $this->layout = 'printhtml';
        Configure::write('debug', 0);
        $conditions = array(
            'Item.id' => $item_id
        );

        $item = $this->Item->find('first', array(
            'conditions' => $conditions,
            'fields' => array('Item.id', 'Item.name', 'Item.code', 'Unit.name')
        ));
        $item['Item']['periode'] = $periode;

        $items = array();
        $penerimaan = 0;
        $item_ins = $this->__getStockIn( $item['Item']['id'], $periode );

        foreach ($item_ins as $key => $item_in) {
            $items[$key]['date_in'] = $item_in['ItemIn']['date_in'];
            $penerimaan += $item_in['ItemIn']['total'];
            $items[$key]['penerimaan_periode'] = $item_in['ItemIn']['total']*1;

            if (!isset($items[$key]['penerimaan']) ) {
                $items[$key]['penerimaan'] = $penerimaan;
            } else {
                $items[$key]['penerimaan'] += $penerimaan;
            }
            $items[$key]['pengeluaran'] = $this->__getStockOut( $item['Item']['id'], $item_in['ItemIn']['created'] );
        }
        $lastItem = $items[count($items)-1];
        $newKey = count($items);

        // if last input barang's date_in is not today,
        // we must count item_outs until today
        if ( $lastItem['date_in'] != $periode ) {
            $lastOut = $this->__getStockOut( $item['Item']['id'], $periode );

            if ( $lastItem['pengeluaran'] != $lastOut ) {
                $items[$newKey]['date_in'] = '';
                $items[$newKey]['penerimaan_periode'] = $lastItem['penerimaan_periode'];
                $items[$newKey]['penerimaan'] = $lastItem['penerimaan'];
                $items[$newKey]['pengeluaran'] = $lastOut;
            }
        }

        $this->set('info', $item);
        $this->set('items', $items);
    }

    function stocks_per_item_ext($item_id, $periode = null) {
        $this->layout = 'printhtml';
        Configure::write('debug', 0);
        $conditions = array(
            'Item.id' => $item_id
        );

        $item = $this->Item->find('first', array(
            'conditions' => $conditions,
            'fields' => array('Item.id', 'Item.name', 'Item.code', 'Unit.name')
        ));
        $item['Item']['periode'] = $periode;

        $items = array();
        $penerimaan = 0;
        $counter = 0;
        $item_ins = $this->__getStockInExt( $item['Item']['id'], $periode );

        foreach ($item_ins as $key => $item_in) {
            $items[$counter]['date_in'] = $item_in['ItemIn']['date_in'];
            $penerimaan += $item_in[0]['total'];
            $items[$counter]['penerimaan_periode'] = $item_in[0]['total']*1;

            if (!isset($items[$counter]['penerimaan_total']) ) {
                $items[$counter]['penerimaan_total'] = $penerimaan;
            } else {
                $items[$counter]['penerimaan_total'] += $penerimaan;
            }

            if ( !isset($stock) ) {
                $stock = $items[$counter]['penerimaan_periode'];
            } else {
                $stock += $items[$counter]['penerimaan_periode'];
            }
            $items[$counter]['pengeluaran'] = 0;
            $items[$counter]['pengebon'] = '';
            $items[$counter]['stock'] = $stock;

            // get item out on current date_in
            // to the next record date_in, if exists.
            // If not exists, compare last date_in
            // with passed period
            if ( isset($item_ins[$counter+1]) ) {
                $item_outs = $this->__getStockOutExt($item['Item']['id'], $item_in['ItemIn']['date_in'], $item_ins[$key+1]['ItemIn']['date_in']);

                $counter++;
                foreach ( $item_outs as $k2 => $item_out ) {
                    $items[$counter]['date_in'] = $item_out['ItemOut']['date_approved'];
                    $items[$counter]['pengeluaran'] = $item_out['ItemOut']['total_approved']*1;
                    // $items[$counter]['penerimaan_periode'] = $stock;
                    $items[$counter]['penerimaan_periode'] = '';
                    $items[$counter]['pengebon'] = $item_out['User']['name'];

                    $stock -= $item_out['ItemOut']['total_approved'];
                    $items[$counter]['stock'] = $stock;
                    $counter++;
                }

            } else if ( $item_in['ItemIn']['date_in'] != $periode ) {
                // if this is the last record
                // compare date_in with passed period
                if ( isset($item_ins[$key+1]['ItemIn']['date_in']) ) {
                    $item_outs = $this->__getStockOutExt($item['Item']['id'], $item_in['ItemIn']['date_in'], $item_ins[$key+1]['ItemIn']['date_in']);
                } else {
                    $item_outs = $this->__getStockOutExt($item['Item']['id'], $item_in['ItemIn']['date_in'], $periode);
                }

                $counter++;
                foreach ( $item_outs as $k3 => $item_out2 ) {
                    $items[$counter]['date_in'] = $item_out2['ItemOut']['date_approved'];
                    $items[$counter]['pengeluaran'] = $item_out2['ItemOut']['total_approved']*1;
                    // $items[$counter]['penerimaan_periode'] = $stock;
                    $items[$counter]['penerimaan_periode'] = '';
                    $items[$counter]['pengebon'] = $item_out2['User']['name'];

                    $stock -= $item_out2['ItemOut']['total_approved'];
                    $items[$counter]['stock'] = $stock;
                    $counter++;
                }

            } else {
                $counter++;
            }
        }

        $this->set('info', $item);
        $this->set('items', $items);

    }

/**
 *  report to show items used by particular role (user or its unit_id)
 *  show form to select unit_id or user_id
 *  Rendering print page on stocks_per_role
 */
    function stocks_per_role_id() {
        $this->set('path', "var path = '" . $this->__pathToController() . "';" );
    }

    function stocks_per_role() {
        $this->layout = 'printhtml';
        Configure::write('debug', 0);
        if ( !empty($this->data) ) {
            $conditions = array(
                'ItemOut.approved' => 1
            );
            $items = array();

            $unit_codes = $this->UnitCode->find('list');
            $units = $this->Item->Unit->find('list', array('fields' => array('Unit.id', 'Unit.name')));

            if ( $this->data['Report']['by'] == 'u' ) {
                // quick hack for all unit code
                if ( $this->data['per'] != '__' ) {
                    $conditions['User.unit_code_id'] = $this->data['per'];
                } else {
                    $this->set('unitAll', 'Semua Unit Kerja');
                }
                $this->set('group', 'UNIT KERJA');
                // $conditions['User.unit_code_id'] = $this->data['per'];
            } else if ( $this->data['Report']['by'] == 'p' ) {
                $conditions['ItemOut.created_by'] = $this->data['per'];
                $this->set('group', 'NAMA');
            }

            $conditions['ItemOut.date_out <='] = date('Y-m-d H:i:s');
            $items = $this->ItemOut->find('all', array(
                'conditions' => $conditions,
                'fields' => array(
                    'ItemOut.id', 'ItemOut.item_id', 'ItemOut.date_out', 'ItemOut.total',
                    'ItemOut.total_approved', 'ItemOut.date_approved',
                    'User.id', 'User.name', 'User.unit_code_id',
                    'Item.id', 'Item.code', 'Item.name', 'Item.unit_id'
                ),
                'order' => 'ItemOut.date_out ASC'
            ));

            $this->set('items', $items);
            $this->set('units', $units);
            $this->set('unit_codes', $unit_codes);
            $this->set('per', $this->data['Report']['by']);
        }
    }

    function __getStockOut($item_id, $periode = null) {
        return $this->ItemOut->getTotal($item_id, $periode);
    }

    function __getStockOutExt($item_id, $date_from, $date_to) {
        return $this->ItemOut->getByDate($item_id, $date_from, $date_to);
    }

    function __getStockIn($item_id, $periode = null) {
        return $this->ItemIn->getTotal($item_id, $periode);
    }

    function __getStockInExt($item_id, $periode = null) {
        return $this->ItemIn->getTotalExt($item_id, $periode);
    }

    function rekapitulasi() {
        $this->set('path', "var path = '" . $this->__pathToController() . "';" );
    }

    function letter_ins() {
        $this->set('path', "var path = '" . $this->__pathToController() . "';" );
    }

    function printhtml() {
        $this->layout = 'printhtml';
        Configure::write('debug', 0);
        if ( !empty($this->data) ) {
            $conditions = array();
            $letters = array();
            if ( $this->params['url']['m'] == 'rekapitulasi' ) {
                if ( $this->data['Report']['by'] == 'u' ) {
                    $conditions['LetterOut.unit_code_id'] = $this->data['per'];
                } else if ( $this->data['Report']['by'] == 'p' ) {
                    $conditions['LetterOut.created_by'] = $this->data['per'];
                }
                $conditions['LetterOut.created <='] = date('Y-m-d H:i:s');
                ClassRegistry::init('LetterOut');
                $this->LetterOut = new LetterOut;
                $letters = $this->LetterOut->find('all', array(
                    'conditions' => $conditions,
                    'order' => 'LetterOut.created DESC'
                ));
                $this->set('m', 'rekapitulasi');
            } else if ( $this->params['url']['m'] == 'letter_ins' ) {
                if ( $this->data['Report']['by'] == 'u' ) {
                    $conditions['LetterIn.unit_code_id'] = $this->data['per'];
                } else if ( $this->data['Report']['by'] == 'p' ) {
                    $conditions['LetterIn.created_by'] = $this->data['per'];
                }
                $conditions['LetterIn.created <='] = date('Y-m-d H:i:s');
                ClassRegistry::init('LetterIn');
                $this->LetterIn = new LetterIn;
                $letters = $this->LetterIn->find('all', array(
                    'conditions' => $conditions,
                    'order' => 'LetterIn.created DESC'
                ));
                $this->set('m', 'letter_ins');
            }
            $this->set('letters', $letters);
            $this->set('per', $this->data['Report']['by']);
        }
    }

    function getuser() {
        ClassRegistry::init('User');
        $this->User = new User;
        $users = $this->User->find('list', array(
            'conditions' => array(
                'User.active' => 1
            ),
            'fields' => array('User.id', 'User.name'),
            'recursive' => -1
        ));
        Configure::write('debug', 0);
        $this->layout = 'ajax';
        $this->set('users', $users);
    }

    function getunit() {
        ClassRegistry::init('UnitCode');
        $this->UnitCode = new UnitCode;
        $units = $this->UnitCode->find('list', array(
            'fields' => array('UnitCode.id', 'UnitCode.name'),
            'recursive' => -1
        ));
        $units['__'] = 'All';
        Configure::write('debug', 0);
        $this->layout = 'ajax';
        $this->set('units', $units);
    }
}
?>
